<template>
	<view class="page-box pad-bottom-200">
		<view class="pad-30 betweenX font-30 color-text">
			<view>全部服务({{saveId.length}})</view>
			<view @click="handleAdmin"> {{isAdmin ? "完成": "管理"}}</view>
		</view>
		<view class="list-box pad-30" v-if="list.length > 0">
			<view class="list pad-30 bg-white radius30" v-for="item in list" :key="item.worker_info.id">
				<view class="centerY">
					<up-checkbox @change="handleChangeAll(item.worker_info.id)"
						:checked="shopAllId.indexOf(item.worker_info.id) != -1" size="30rpx" labelSize="26rpx"
						shape="circle" usedAlone :customStyle="{marginTop: '8rpx'}">
					</up-checkbox>
					<view class="address centerY">
						<image class="avatar" :src="item.worker_info.avatar" mode="aspectFill"></image>
						<view class="mar-left-10 font-30 font-w-500">{{item.worker_info.name}}</view>
					</view>
				</view>
				<view class="flex mar-top-30" v-for="info in item.works" :key="info.cart_detail_id">
					<up-checkbox placement="column" @change="handleChange(item.worker_info.id,info.cart_detail_id)"
						:customStyle="{marginTop: '8rpx'}" :checked="saveId.indexOf(info.cart_detail_id) != -1"
						size="30rpx" labelSize="26rpx" shape="circle" usedAlone>
					</up-checkbox>
					<view class="flex-w">
						<view class="betweenX font-30 font-w-400">
							<view class="flex-w color-646464">{{info.work_name}}</view>
							<view class="color-error">￥{{orderPrice(info)}}</view>
						</view>
						<view class="font-24 color-646464">
							<view class="mar-top-30">已选服务： x{{info.num}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 缺省组件 -->
		<view v-if="list.length == 0" class="centerXY columnY">
			<u-empty marginTop="100" width="75" height="75" text="购物车竟然是空的" icon="/static/image/car-none.png"></u-empty>
			<view @click="hanldeHome" class="btn font-24 mar-top-80 button-style">去首页逛逛</view>
		</view>
	</view>


	<!-- bottom -->
	<view class="betweenX button-bottom centerXY">
		<view class="font-26 left">
			<up-checkbox @change="selectAll" size="30rpx" labelSize="26rpx" shape="circle" usedAlone
				:customStyle="{marginBottom: '0rpx'}" label="全选" :checked="aloneChecked">
			</up-checkbox>
		</view>
		<view class="centerXY betweenX" v-if="!isAdmin">
			<view class="font-24 text-right">
				<view class="color-text">已选{{saveId.length}}件，合计：<text class="color-error">￥</text> <text
						class="color-error font-36">{{totalAmount}}</text></view>
			</view>
			<view @click="hanldeSave" class="btn font-24 mar-left-20 button-style">去结算</view>
		</view>
		<view class="centerXY betweenX" v-else>
			<view class="font-24 text-right">
				<view class="color-text">已选{{saveId.length}}件</view>
			</view>
			<view @click="handleDelete" class="btn font-24 mar-left-20 button-error">删除</view>
		</view>
	</view>
	
	<suspend icon="/static/image/service.jpg"></suspend>
</template>

<script setup>
	// 引入decimal.js 保证显示不失真
	import Decimal from 'decimal.js';

	import {
		ref
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		serviceCartAll,
		serviceCartDel
	} from '@/api/index.js'


	// 跳转首页
	const hanldeHome = () => {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}

	// 单价计算
	const orderPrice = (item) => {
		if(item.order_price)
		return new Decimal(item.order_price).mul(new Decimal(item.min_buy_num))
			.toNumber().toFixed(2);
	}

	// 提交选中的id
	// 店铺id
	let shopAllId = ref([]);
	// 商品id
	let saveId = ref([]);
	// 组装去订单
	const hanldeSave = () => {
		// 组装完成
		const result = list.value.map(item => {
			const filteredIds = item.works.filter(idObj => idObj?.isShow === true);
			return {
				worker_id: item.worker_info.id,
				work_ids: filteredIds.map(i => i.work_id)
			};
		}).filter(item => item.work_ids.length > 0);
		if (result.length > 0) {
			uni.navigateTo({
				url: `/pages/order/confirmOrder/confirmOrder?type=car&data=${JSON.stringify(result)}`
			})
			shopAllId.value = [];
			saveId.value = [];
			
			// 监听全选
			isChecked();
			totalAmount.value = '0.00';
			isAdmin.value = false;
		} else {
			uni.$u.toast('请选择要结算的!');
		}
	}

	// 移出购物车
	const handleDelete = () => {
		// 删除接口
		serviceCartDel({
			ids: saveId.value
		}).then(res => {
			// 删除父级
			list.value = list.value.filter(item => !shopAllId.value.includes(item.worker_info.id));
			list.value.forEach(shop => {
				// 删除子级
				shop.works = shop.works.filter(shop => !saveId.value.includes(shop.cart_detail_id));
			});

			// 清空 选中的id
			shopAllId.value = [];
			saveId.value = [];

			// 监听全选
			isChecked();
			isAdmin.value = false;

			uni.$u.toast(res.msg);
		});
	}

	// 全选
	const aloneChecked = ref(false);
	const selectAll = () => {
		aloneChecked.value = !aloneChecked.value;
		if (aloneChecked.value) {
			list.value.forEach(shop => {
				shopAllId.value.push(shop.worker_info.id);
				shop.works.forEach(info => {
					saveId.value.push(info.cart_detail_id);
					info.isShow = true;
					countAmount(info, 'add');
				})
			})
		} else {
			saveId.value = [];
			shopAllId.value = [];
			totalAmount.value = '0.00';
		}
	}

	// 选择商品
	const handleChange = (shopId, id) => {
		const shopItem = list.value.find(shop => shop.worker_info.id == shopId);
		// 存储当前店铺 选择几个
		let num = 0;
		if (shopItem) {
			const goodsItem = shopItem.works.find(goods => goods.cart_detail_id == id);
			if (goodsItem) {
				// push 选中的商品Id
				if (saveId.value.includes(id)) {
					saveId.value = saveId.value.filter(i => i !== id);
					goodsItem.isShow = false;
					countAmount(goodsItem, 'sub');
				} else {
					saveId.value.push(id);
					goodsItem.isShow = true;
					countAmount(goodsItem, 'add');
				}

				shopItem.works.forEach(item => {
					if (saveId.value.includes(item.cart_detail_id)) {
						num++;
					}
				})

				// 选择店铺
				if (num == shopItem.works.length) {
					shopAllId.value.push(shopId);
				} else {
					shopAllId.value = shopAllId.value.filter(i => i !== shopId);
				}
			}
		}

		// 监听全选
		isChecked();
	}

	// 选择店铺
	const handleChangeAll = (shopId) => {
		const shopItem = list.value.find(shop => shop.worker_info.id == shopId);
		if (shopAllId.value.includes(shopId)) {
			shopAllId.value = shopAllId.value.filter(i => i !== shopId);
			shopItem.works.forEach(item => {
				item.isShow = false;
				saveId.value = saveId.value.filter(i => i !== item.cart_detail_id);
				countAmount(item, 'sub')
			})
		} else {
			shopAllId.value.push(shopId);
			shopItem.works.forEach(item => {
				item.isShow = true;
				saveId.value.push(item.cart_detail_id);
				countAmount(item, 'add')
			})
		}
		// 监听全选
		isChecked();
	}

	// 计算选中的金额
	let totalAmount = ref(0);
	const countAmount = (item, type) => { // type加减乘除 add，sub，mul，div
		if(item.order_price);
		if (type == 'add') {
			totalAmount.value = new Decimal(totalAmount.value).add(new Decimal(item.order_price).mul(Decimal(item
				.min_buy_num))).toNumber().toFixed(2);
		} else if (type == 'sub') {
			totalAmount.value = new Decimal(totalAmount.value).sub(new Decimal(item.order_price).mul(Decimal(item
				.min_buy_num))).toNumber().toFixed(2);
		}
	}

	// 监听是否全选
	const isChecked = () => {
		if (shopAllId.value.length == 0) {
			aloneChecked.value = false;
			return
		}
		if (shopAllId.value.length == list.value.length) {
			aloneChecked.value = true;
		} else {
			aloneChecked.value = false;
		}
	}

	// 购物车模拟数据
	let list = ref([])
	// 管理
	let isAdmin = ref(false);
	const handleAdmin = () => {
		isAdmin.value = !isAdmin.value;
	}
	// 获取所有的 购物车
	const getServiceCartAll = () => {
		serviceCartAll().then(res => {
			list.value = res.data.lists;
		})
	}

	onShow(() => {
		getServiceCartAll();
	})
</script>

<style scoped lang="scss">
	.info {
		display: flex;
		justify-content: flex-end;
	}

	.avatar {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
	}

	.left {
		width: 100rpx;
	}

	.button-bottom {
		width: 100%;
		padding: 30rpx;
		box-sizing: border-box;
		background: white;
		position: fixed;
		bottom: 100rpx;
		// #ifdef MP-WEIXIN
		bottom: 0rpx;
		// #endif 
		z-index: 2;
	}

	.btn {
		width: 200rpx;
		height: 80rpx;
		border-radius: 50rpx;
		border: 2rpx solid #C1C1C1;
		line-height: 80rpx;
		text-align: center;
	}

	.list {
		margin-bottom: 30rpx;
	}

	.list ::v-deep .u-checkbox {
		display: flex;
		align-items: flex-start;
	}

	.list-box {
		padding-bottom: 150rpx;
	}
</style>